/**
 * Created by Administrator on 2016/12/01.
 */
package com.cplatform.movie.back.javamail;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.Session;
import javax.mail.PasswordAuthentication;



public class Email {
    private static final String host = "smtp.sina.com";
    private static final String home_address = "xiaoyuqwe123@sina.com";
    private static final String password = "123456789";
    // 服务实体类
    private transient EmailServiceEnity emailService;
    // 回复内容
    private transient String content;

    public static void sendMail(String target_address){
        Properties props = System.getProperties();
        props.put("mail.smtp.host",host);
        props.put("mail.smtp.auth","true");
        Session session = Session.getDefaultInstance(props,new Authenticator(){
            @Override
            public PasswordAuthentication getPasswordAuthentication(){
                return  new PasswordAuthentication(home_address,password);
            }
        });
        try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(home_address));
            message.addRecipient(Message.RecipientType.TO,new InternetAddress(
                    target_address));
            message.setSubject("JAVA");
            message.setText("Do you like me?");
            Transport.send(message);
        }catch (MessagingException e){
            e.printStackTrace();
        }
    }



    public void replyEmail () throws MessagingException, IOException {
        // 获取邮件,和查看邮件相同,调用方法即可
        LookEmailService lookEmail = new LookEmailService();
        emailService = new EmailServiceEnity("", "",EmailServiceEnity.MAIL_PROTOCOL_POP3);
        lookEmail.setEmailService(emailService);
        Message message = lookEmail.getMessageByIndex(lookEmail.getAllMessage().length);

        /*************上面为获取邮件************到此处是一个分水岭****************下面为发送邮件****************/
        Message reply = this.newReplyMessage(message);

        // 布尔值，true为回复给所有人，false为只回复给发送者
        reply.reply(true);

        // 发送回复
        emailService.getTransport().connect();
        emailService.getTransport().sendMessage(reply, reply.getAllRecipients());
        emailService.getTransport().close();
    }

    /**
     * 组装要回复的邮件
     * @param message
     * @return
     * @throws MessagingException
     * @throws IOException
     */
    public Message newReplyMessage(Message message) throws MessagingException, IOException {
        // 出新初始化一个服务类，因为之前为获取邮件，协议为POP3，当前要发送邮件，协议为SMTP
        emailService = new EmailServiceEnity("", "", EmailServiceEnity.MAIL_PROTOCOL_SMTP);

        // 新创建一个邮件
        Message reply = emailService.getMessage();

        // 获取原邮件的发件人--》为新邮件的接收人
        Address[] addressTo = message.getFrom();

        // 获取原邮件内容（暂支持文本和HTML单部件，多部件另需递归循环原邮件，并新增）
        Object content = message.getContent();

        // 获取原邮件主题
        String subObject = message.getSubject();

        // 获取邮件发送时间
        String date = message.getSentDate().toString();

        /** 组装新邮件*/
        // 设置回复内容，新内容+原文
        reply.setContent(this.content + "<br/><br/><br/>" + date +","+
                InternetAddress.toString(addressTo) + "写到:<br/>> " +
                content, "text/html;charset=utf-8");

        // 设置邮件回复主题
        reply.setSubject("Re：" + subObject);

        // 设置收件人：原发件人
        reply.addRecipients(Message.RecipientType.TO, addressTo);

        return reply;
    }


    public static void main(String[] args) {
        Email.sendMail("841779262@qq.com");
        Email.sendMail("1535764143@qq.com");
        try {
            ReplyEmailService replySend = new ReplyEmailService();
            replySend.setContent("你好，邮件已收到！ <a href='http://www.cnblogs.com/liuyitian'><<--点击进入我的博客-->></a>");
            replySend.replyEmail();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public EmailServiceEnity getEmailService() {
        return emailService;
    }
    public void setEmailService(EmailServiceEnity emailService) {
        this.emailService = emailService;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}



